<?php
namespace Weixin\Controller;
use Think\Controller;
class IndexController extends Controller {
	public function index(){
		//接受post,或者get
		$this->save();
		define("TOKEN", "e3CFNGAieW3RCFN");
		
		//接口验证
		if(I('get.echostr')){
			$this->valid();
		}
		
		//接受XML信息
		$this->responseMsg();
		//$file_in = file_get_contents("php://input"); //接收post数据
		
		//$xml = simplexml_load_string($file_in);//转换post数据为simplexml对象
		
		//消息接受
		
		//回复消息
	}
	
	//微信接口验证
	public function valid()
	{
		$echoStr = I('get.echostr');
	
		//valid signature , option
		if($this->checkSignature()){
			echo $echoStr;
			exit;
		}
	}
	
	//验证
	private function checkSignature()
	{
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }
        
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        		
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
	
	//获取access_token
	public function get_access_token(){
		//$header[] = "Content-type: text/xml";        //定义content-type为xml,注意是数组
		$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.C('APPID').'&secret='.C('APPSECRET');
		$ch = curl_init ();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, 0);
		
		$response = curl_exec($ch);
		if(curl_errno($ch)){
			print curl_error($ch);
		}
		curl_close($ch);
		return $response;
	}
	
	public function responseMsg()
	{
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		if (!empty($postStr)){
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$fromUsername = (string)$postObj->FromUserName;
			$toUsername = (string)$postObj->ToUserName;
			$keyword = trim($postObj->Content);
			$createTime = (int)$postObj->CreateTime;
			$msgType = (string)$postObj->MsgType;
			$time = time();
			$textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <Content><![CDATA[%s]]></Content>
            <FuncFlag>0<FuncFlag>
            </xml>";
			if(!empty( $keyword ))
			{
				//$this->save($toUsername);
				$msgType = "text";
				$contentStr = '我现在还小, 等我长大后再回答你的问题';
				//保存信息
				$data['openID'] = $fromUsername;
				$data['toUserName'] = $toUsername;
				$data['content'] = $keyword;
				$data['createTime'] = $createTime;
				$data['msgType'] = $msgType;
				
				//保存信息
				M('weixin')->add($data);
				$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
				echo $resultStr;
			}else{
				echo '咋不说哈呢';
			}
		}else {
			echo '咋不说哈呢';
			exit;
		}
	}
	
	//保存post信息
	public function save($data = null){
		if(!$data){
			if(IS_POST){
				$data = file_get_contents("php://input"); //接收post数据
			}else{
				$data = $_GET;
			}
		}
		//$file_in = file_get_contents("php://input"); //接收post数据
		$info['data'] = serialize($data);
		$info['create_time'] = NOW_TIME;
		$info['ip'] = get_client_ip(0, true);
		$result = M('post_log')->add($info);
			
	}
}